//
//  SISSCustomMorePopupView.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/11/26.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSCustomMorePopupView.h"

#import "MMLeftCell.h"
#import "MMComboBoxHeader.h"
#import "MMNormalCell.h"
#import "MMSelectedPath.h"
#import "SISSCustomMoreItem.h"
@interface SISSCustomMorePopupView () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, assign) BOOL isSuccessfulToCallBack;
@property (nonatomic, assign) NSUInteger minRowNumber;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) NSMutableArray *tableViewArrays;
@property (nonatomic, strong) SISSCustomMoreItem *item;
@property (nonatomic, assign) NSInteger leftSelectedRow;
@end
@implementation SISSCustomMorePopupView

- (id)initWithItem:(MMItem *)item{
    self = [super init];
    if (self) {
        self.item = (SISSCustomMoreItem *)item;
        self.minRowNumber = 6;
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
        //遍历MMItems
        for (int i = 0; i < self.item.childrenNodes.count; i++) {
            MMItem *subItem = item.childrenNodes[i];
            NSMutableArray *itemsArray = [NSMutableArray array];
            for (int j = 0; j <subItem.childrenNodes.count; j++) {
                MMItem *secondItem = subItem.childrenNodes[j];
                if (secondItem.isSelected == YES){
                    [itemsArray addObject:[MMSelectedPath pathWithFirstPath:i secondPath:j]];
                }
            }
            if (itemsArray.count == 0) {
                [itemsArray addObject:[MMSelectedPath pathWithFirstPath:i secondPath:0]];
            }
            [self.selectedArray addObject:itemsArray];
        }
        
        self.temporaryArray = [[NSArray alloc] initWithArray:self.selectedArray copyItems:YES];
    }
    return self;
}

#pragma mark - public method
- (void)popupViewFromSourceFrame:(CGRect)frame completion:(void (^ __nullable)(void))completion {
    UIView *rootView = [[UIApplication sharedApplication] keyWindow];
    self.sourceFrame = frame;
#pragma mark- 增加kTopHeight
    CGFloat top =  CGRectGetMaxY(self.sourceFrame) + kTopHeight;
    CGFloat maxHeight = kScreenHeigth - DistanceBeteewnPopupViewAndBottom - top - PopupViewTabBarHeight;
    CGFloat resultHeight = MIN(maxHeight, MAX(self.item.childrenNodes.count, self.minRowNumber)  * PopupViewRowHeight);
    self.frame = CGRectMake(0, top, kScreenWidth, 0);
    [rootView addSubview:self];
    
    //add tableView
    NSUInteger numberOftableViews = 2;
    //    CGFloat firstTableViewRowHeight =(self.minRowNumber > self.item.childrenNodes.count)?(PopupViewRowHeight*self.minRowNumber/self.item.childrenNodes.count):PopupViewRowHeight;
#pragma mark- 更改firstTableViewRowHeight
    CGFloat firstTableViewRowHeight = PopupViewRowHeight;
    for (NSInteger index = 0; index < numberOftableViews; index ++) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.rowHeight = (index == 0)?firstTableViewRowHeight:PopupViewRowHeight;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tag = index;
        tableView.tableFooterView = [UIView new];
        if (index == 0) {
             self.mainTableView = tableView;
            [tableView registerClass:[MMLeftCell class] forCellReuseIdentifier:MainCellID];
        }else {
            [tableView registerClass:[MMNormalCell class] forCellReuseIdentifier:SubCellID];
        }
        [self addSubview:tableView];
        [self.tableViewArrays addObject:tableView];
        
    }
    
    //add ShadowView
    self.shadowView.frame = CGRectMake(0, top, kScreenWidth, kScreenHeigth - top);
    self.shadowView.alpha = 0;
    self.shadowView.userInteractionEnabled = YES;
    [rootView insertSubview:self.shadowView belowSubview:self];
    UITapGestureRecognizer  *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(respondsToTapGestureRecognizer:)];
    tap.numberOfTouchesRequired = 1; //手指数
    tap.numberOfTapsRequired = 1; //tap次数
    [self.shadowView addGestureRecognizer:tap];
    
    //出现的动画
    LeftCellWidth = 100.0f;
    [UIView animateWithDuration:AnimationDuration animations:^{
        self.frame = CGRectMake(0, top, kScreenWidth, resultHeight);
        for (int index = 0; index < self.tableViewArrays.count; index ++) {
            UITableView *tableView = self.tableViewArrays[index];
            BOOL isFirstIndex = (index == 0);
            tableView.frame = CGRectMake(isFirstIndex?0:LeftCellWidth + 1, 0, isFirstIndex?LeftCellWidth:(self.width - LeftCellWidth), self.height);
            
        }
        self.shadowView.alpha = ShadowAlpha;
        
    } completion:^(BOOL finished) {
        completion();
        self.height += PopupViewTabBarHeight;
        self.bottomView = [[UIView alloc] init];
        self.bottomView.backgroundColor = [UIColor colorWithHexString:@"FCFAFD"];
        self.bottomView.frame = CGRectMake(0, self.mainTableView.bottom, self.width, 60);
        [self addSubview:self.bottomView];
        
        
        NSArray *titleArray = @[@"重置",@"确定"];
        for (int i = 0; i < 2 ; i++) {
            CGFloat left = ((i == 0) ? self.width * 0.15 : self.width * 0.65);
            UIColor *titleColor = ((i == 0)?[UIColor blackColor]:[UIColor colorWithHexString:titleSelectedColor]);
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(left, 10, 100, PopupViewTabBarHeight);
            button.tag = i;
            button.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
            button.layer.borderWidth = 1;
            button.layer.cornerRadius = 2;
            button.layer.masksToBounds = YES;
            [button setTitle:titleArray[i] forState:UIControlStateNormal];
            [button setTitleColor:titleColor forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:ButtonFontSize];
            [button addTarget:self action:@selector(respondsToButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.bottomView addSubview:button];
        }
    }];
    
}

- (void)dismiss{
    [super dismiss];
    if (self.isSuccessfulToCallBack == NO) {
        [self _resetValue];
    }
    if ([self.delegate respondsToSelector:@selector(popupViewWillDismiss:)]) {
        [self.delegate popupViewWillDismiss:self];
    }
    
#pragma mark- 增加kTopHeight
    CGFloat top =  CGRectGetMaxY(self.sourceFrame) + kTopHeight;
    //消失的动画
    [UIView animateWithDuration:AnimationDuration animations:^{
        //        self.imageView.hidden = YES;
        self.frame = CGRectMake(0, top, kScreenWidth, 0);
        for (UITableView *tableView in self.tableViewArrays) {
            tableView.height = self.height;
        }
        self.shadowView.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (self.superview) {
            [self removeFromSuperview];
        }
    }];
}

#pragma mark - private method
- (void)_callBackDelegate {
    if ([self.delegate respondsToSelector:@selector(popupView:didSelectedItemsPackagingInArray:atIndex:)]) {
        self.isSuccessfulToCallBack = YES;
        [self.delegate popupView:self didSelectedItemsPackagingInArray:self.selectedArray  atIndex:self.tag];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismiss];
            self.isSuccessfulToCallBack = NO;
        });
    }
}


//重置
- (void)_resetValue {
    [self.selectedArray removeAllObjects];
    self.leftSelectedRow = 0;
    for (int i = 0; i < self.item.childrenNodes.count; i++) {
        MMItem *subItem = self.item.childrenNodes[i];
        subItem.isSelected = NO;
        NSMutableArray *itemsArray = [NSMutableArray array];
        for (int j = 0; j <subItem.childrenNodes.count; j++) {
            subItem.childrenNodes[j].isSelected = NO;
            if (j == 0){
                [itemsArray addObject:[MMSelectedPath pathWithFirstPath:i secondPath:j]];
            }
        }
        [self.selectedArray addObject:itemsArray];
    }

    [self.tableViewArrays[0] reloadData];
    [self.tableViewArrays[1] reloadData];
}


#pragma mark - Action
- (void)respondsToButtonAction:(UIButton *)sender {
    if (sender.tag == 0) {
        [self _resetValue];
    } else if (sender.tag == 1) {//确定
        [self _callBackDelegate];
    }
}

- (void)respondsToTapGestureRecognizer:(UITapGestureRecognizer *)tapGestureRecognizer {
    [self dismiss];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (tableView.tag) {
        case 0:
            return self.item.childrenNodes.count;
            break;
        case 1:
            return self.item.childrenNodes[self.leftSelectedRow].childrenNodes.count;
            break;

        default:
            break;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 0) { //mainTableView
        MMLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:MainCellID forIndexPath:indexPath];
        cell.item = self.item.childrenNodes[indexPath.row];
        return cell;
    }
    MMNormalCell *cell = [tableView dequeueReusableCellWithIdentifier:SubCellID forIndexPath:indexPath];
    cell.item = self.item.childrenNodes[self.leftSelectedRow].childrenNodes[indexPath.row];
//    cell.backgroundColor = [UIColor colorWithHexString:@"F5F3F6"];
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    switch (tableView.tag) {
        case 0:{
            //清除之前的选中状态
            NSInteger indexOfSelectedArray = [self _indexOfSelectedArrayByPath:[MMSelectedPath pathWithFirstPath:indexPath.row secondPath:indexPath.section]];
            for (int i = 0; i < self.item.childrenNodes.count; i++) {
                MMItem *subItem = self.item.childrenNodes[i];
                NSArray<MMSelectedPath *> *arr = self.selectedArray[i];
                if (arr.firstObject.secondPath == 0) {
                    subItem.isSelected = NO;
                }
                if (i != indexOfSelectedArray && subItem.childrenNodes.firstObject.isSelected == YES) {
                    subItem.isSelected = NO;
                    subItem.childrenNodes.firstObject.isSelected = NO;
                }
            }

            //设置现在的选中状态
            self.item.childrenNodes[indexPath.row].isSelected = YES;
            self.leftSelectedRow = indexPath.row;
            
            //刷新
            [self.tableViewArrays[0] reloadData];
            [self.tableViewArrays[1] reloadData];
            
            break;}
        case 1:{
            NSInteger indexOfSelectedArray = [self _indexOfSelectedArrayByPath:[MMSelectedPath pathWithFirstPath:self.leftSelectedRow secondPath:indexPath.row]];
            NSMutableArray *itemArray = self.selectedArray[indexOfSelectedArray];
            MMItem *subItem = self.item.childrenNodes[self.leftSelectedRow];
            for (int j = 0; j <subItem.childrenNodes.count; j++) {
                MMItem *secondItem = subItem.childrenNodes[j];
                secondItem.isSelected = NO;
            }
            // 设置现在的选中状态
            MMItem *currentIndex =self.item.childrenNodes[self.leftSelectedRow].childrenNodes[indexPath.row];
            currentIndex.isSelected = YES;
            //移除
            [itemArray removeAllObjects];
            //添加
            [itemArray addObject:[MMSelectedPath pathWithFirstPath:self.leftSelectedRow secondPath:indexPath.row]];
            
            UITableView *secondTableView = self.tableViewArrays[1];
            [secondTableView reloadData];

            break;}
    
        default:
            break;
    }
}


#pragma mark - Private Method
- (NSInteger)_indexOfSelectedArrayByPath:(MMSelectedPath *)path {
    return path.firstPath;;
}

- (NSMutableArray *)tableViewArrays {
    if (_tableViewArrays == nil) {
        _tableViewArrays = [NSMutableArray array];
    }
    return _tableViewArrays;
}


@end
